﻿import tkinter as tk
from tkinter import ttk, messagebox

class LotteryAnalyzerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("彩票分析工具 v2.0")
        self.root.geometry("800x600")
        
        self.style = ttk.Style()
        self.style.theme_use('clam')
        
        self.create_widgets()
    
    def create_widgets(self):
        main_frame = ttk.Frame(self.root, padding=10)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 数据输入区域
        input_frame = ttk.LabelFrame(main_frame, text="输入参数", padding=10)
        input_frame.pack(fill=tk.X, pady=5)

        ttk.Label(input_frame, text="增加值：").grid(row=0, column=0, padx=5, sticky=tk.W)
        self.entry_value = ttk.Entry(input_frame, width=10)
        self.entry_value.grid(row=0, column=1, padx=5, sticky=tk.W)

        # 期数数据输入
        data_frame = ttk.LabelFrame(main_frame, text="输入各期数据（每行一期，7个数字用空格分隔）", padding=10)
        data_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.text_data = tk.Text(data_frame, height=10, wrap=tk.NONE)
        scroll_y = ttk.Scrollbar(data_frame, orient=tk.VERTICAL, command=self.text_data.yview)
        scroll_x = ttk.Scrollbar(data_frame, orient=tk.HORIZONTAL, command=self.text_data.xview)
        self.text_data.configure(yscrollcommand=scroll_y.set, xscrollcommand=scroll_x.set)
        
        self.text_data.grid(row=0, column=0, sticky="nsew")
        scroll_y.grid(row=0, column=1, sticky="ns")
        scroll_x.grid(row=1, column=0, sticky="ew")

        # 示例数据
        example_data = """16 04 26 19 21 29 13
21 04 37 09 14 01 45
29 32 19 25 26 39 04
04 19 20 39 30 11 45
43 38 42 09 01 14 23
04 25 15 22 29 42 01
07 11 25 15 17 28 09
01 47 40 11 06 02 32
14 15 44 20 27 41 33
41 20 22 27 44 13 36"""
        self.text_data.insert(tk.END, example_data)

        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(pady=10)
        
        self.btn_analyze = ttk.Button(btn_frame, text="开始分析", command=self.analyze)
        self.btn_analyze.pack(side=tk.LEFT, padx=5)
        
        self.btn_export = ttk.Button(btn_frame, text="导出结果", command=self.export_results)
        self.btn_export.pack(side=tk.LEFT, padx=5)

        # 结果显示
        result_frame = ttk.LabelFrame(main_frame, text="分析结果", padding=10)
        result_frame.pack(fill=tk.BOTH, expand=True)

        columns = ("位置", "命中次数")
        self.tree = ttk.Treeview(result_frame, columns=columns, show="headings", height=8)
        
        self.tree.heading("位置", text="位置")
        self.tree.heading("命中次数", text="命中次数")
        self.tree.column("位置", width=150, anchor=tk.CENTER)
        self.tree.column("命中次数", width=150, anchor=tk.CENTER)

        scroll_result = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scroll_result.set)
        
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scroll_result.pack(side=tk.RIGHT, fill=tk.Y)

        # 状态栏
        self.status_bar = ttk.Label(self.root, text="就绪", relief=tk.SUNKEN, anchor=tk.W)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

    def parse_input_data(self):
        raw_data = self.text_data.get("1.0", tk.END).strip()
        if not raw_data:
            raise ValueError("请输入各期数据")
        
        periods = []
        for line in raw_data.split('\n'):
            line = line.strip()
            if not line:
                continue
            # 转换所有数字为整数
            numbers = []
            for num in line.split():
                try:
                    n = int(num)
                    if n < 1 or n > 49:
                        raise ValueError(f"数字 {n} 超出范围（1-49）")
                    numbers.append(n)
                except ValueError:
                    raise ValueError(f"无效数字: {num}")
            
            if len(numbers) != 7:
                raise ValueError(f"每期需要7个数字，当前行有 {len(numbers)} 个数字")
            
            periods.append(numbers)
        
        # 反转顺序使其符合原始数据结构（最新一期在最前面）
        return periods[::-1]

    def calculate_hits(self, add_value, periods):
        counters = [0] * 7
        if len(periods) < 2:
            raise ValueError("至少需要两期数据进行计算")
        
        for i in range(len(periods) - 1):
            current = periods[i]
            next_period = periods[i+1]
            next_numbers = set(next_period)
            
            for pos in range(7):
                num = current[pos]
                adjusted = (num + add_value - 1) % 49 + 1
                if adjusted in next_numbers:
                    counters[pos] += 1
        return counters

    def analyze(self):
        try:
            # 获取并验证增加值
            add_value = int(self.entry_value.get())
            if add_value < 1 or add_value > 48:
                raise ValueError("增加值需在1-48之间")
            
            # 解析输入数据
            periods = self.parse_input_data()
            
            # 计算结果
            results = self.calculate_hits(add_value, periods)
            
            # 清空旧数据
            for item in self.tree.get_children():
                self.tree.delete(item)
            
            # 显示结果
            for idx, count in enumerate(results):
                position = f"位置{idx+1}"
                self.tree.insert("", tk.END, values=(position, count))
            
            self.status_bar.config(text=f"分析完成 - 使用{len(periods)}期数据，增加值: {add_value}")
        
        except Exception as e:
            messagebox.showerror("分析错误", str(e))
            self.status_bar.config(text="分析出错")

    def export_results(self):
        if not self.tree.get_children():
            messagebox.showwarning("导出警告", "没有可导出的数据")
            return
        
        try:
            with open("analysis_result.txt", "w", encoding="utf-8") as f:
                f.write(f"增加值分析结果：{self.entry_value.get()}\n")
                f.write("输入数据：\n")
                f.write(self.text_data.get("1.0", tk.END))
                f.write("\n分析结果：\n")
                for item in self.tree.get_children():
                    values = self.tree.item(item)["values"]
                    f.write(f"{values[0]}: {values[1]}次\n")
            messagebox.showinfo("导出成功", "结果已保存到 analysis_result.txt")
        except Exception as e:
            messagebox.showerror("导出失败", f"发生错误：{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = LotteryAnalyzerApp(root)
    root.mainloop()